
var sdui={
    "dt":"202405190800",
    "n":"ER01",
    "ybs":"1","ybe":"10",
    "ops":[{"t":"add","r":"rain.geojson","v":"100"}],
    "ret":"SUM"
};
// convert 1,2,3 to '001','002','003'
function i2s(ival){
	return String(ival+1000).substr(1);
}

function main() {
    let dt= Number(sdui.dt);//起报时间
    let dsNameRoot="CMA/"+sdui.n+"/P";
    let ybStart=Number(sdui.ybs);
    let ybEnd  =Number(sdui.ybe);
    let dsNameArr=[];
    for(let ii=ybStart;ii<=ybEnd;++ii){
    	dsNameArr.push(dsNameRoot+i2s(ii));
    }
    //构建一个空的数据集保存操作结果
    let resDs=pe.NewDataset(6,256,256,1,0);//6表示为float型
    for(let op of sdui.ops)
    {
    	if( op.t==="add"){
    		let tval=Number(op.v);
    		let tgeom=pe.geomById(op.r);
    		let tds =pe.NewDataset(6,256,256,1,0); 
    		tds=tds.burn(tgeom,tval);
    		resDs=resDs.add(tds,0,32760,0);
    	}else if( op.t==="sub") {
    		let tval=Number(op.v);
    		let tgeom=pe.geomById(op.r);
    		let tds =pe.NewDataset(6,256,256,1,0); 
    		tds=tds.burn(tgeom,tval);
    		resDs=resDs.sub(tds,0,32760,0);
    	}
    }
    //将开始预报和结束预报时间范围内的降水数据求和
    let sum0Ds = pe.NewDataset(6,256,256,1,0);
    for( let name1 of dsNameArr )
    {
    	let tds = pe.Dataset(name1, dt);
    	sum0Ds=sum0Ds.add(tds,0,32760,0);
    }
    //将操作结果与预报结果再次求和
    resDs=resDs.add(sum0Ds,0,32760,0);

    if( sdui.ret==="SUM") {
    	//返回操作后汇总结果
    	return resDs;
    }else{
    	//返回操作后某一个预报时刻结果
    	let ret=Number(sdui.ret);
    	let name1="CMA/"+sdui.n+"/P"+i2s(ret);
    	let ds1=pe.Dataset(name1,dt);
    	ds1=ds1.forEachPixel(function(va,ind){
    		let oldval=va[0];
    		let oldsum=sum0Ds.tiledata[ind];
    		let ratio=0.0;
    		if(oldsum>0.0)ratio=oldval/oldsum;
    		return ratio*resDs.tiledata[ind];
    	});
    	return ds1;
    }
}